﻿/**
 * @file Socket.h
 * @brief Socket封装
 * $Id: Socket.h 13 2011-01-01 11:48:27Z tonyjobmails $
 * $Date: 2011-01-01 11:48:27 +0000 (Sat, 01 Jan 2011) $
 * $Author: tonyjobmails $
 * $Revision: 13 $
 */

#ifndef __SOCKET__H
#define __SOCKET__H

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "DyByteBuff.h"
#include "StcByteBuff.h"

#define MIN_ZIP_LEN(x) ((x + 12) * 11 / 10)

class Socket
{
	public:
		/// max packet size
		static const unsigned int _MAX_PACKET_SIZE = _UNIT_BUFF_SIZE - 1;
		/// packet head size
		static const unsigned int _PACKET_HEAD_SIZE = sizeof(unsigned int);
		/// max data size
		static const unsigned int _MAX_PACKET_DATA_SIZE = _MAX_PACKET_SIZE - _PACKET_HEAD_SIZE;
		/// the mask of the packet length
		static const unsigned int _PACKET_LEN_MASK = _MAX_PACKET_SIZE;
		/// flag of compress
		static const unsigned int _PACKET_ZIP_FLAG = 0x80000000;
		/// flag of enc
		static const unsigned int _PACKET_ENC_FLAG = 0x04000000;

	private:
		void setNonblock();

	public:
		Socket(int sock);
		~Socket();

	private:
		/// 拆包
		unsigned int unpacket(const unsigned char *in, const unsigned int len, StcByteBuff &buffer);
		/// 封包
		unsigned int packet(const unsigned char *in, const unsigned int len, StcByteBuff &buffer);

		/// 得到包长
		unsigned int packetLen(const unsigned char *packet);
		/// 得到数据部分长度
		unsigned int packetDataLen(const unsigned char *packet);


	public:
		/// 发送缓冲区数据
		int send_buff();
		/// 发送数据到缓冲
		int send_to_buff(const unsigned char *data, const unsigned int size);
		/// 直接发送数据
		int send_im(const unsigned char *data, const unsigned int size)

		/// 接受数据到缓冲区
		int recv_buff();
		/// 从缓冲区中取数据
		int recv_from_buff(unsigned char *data, const unsigned int size);

		/// 加入EPOLL事件
		int addEpoll(int epollfd, __uint32_t events, void* ptr);
		/// 删除EPOLL事件
		int delEpoll(int epollfd, __uint32_t events);

	private:
		int _M_sockfd;				/// socket fd
		struct sockaddr_in _M_addr;		/// 远端地址
		struct sockaddr_in _M_local_addr;	/// 本地地址

		DyByteBuff _M_rd_buff;			/// 接受缓冲
		DyByteBuff _M_wr_buff;			/// 发送缓冲
};

#endif	/// __SOCKET__H
